package com.szy.douyou_gateway.config;

import cn.hutool.core.bean.BeanUtil;
import com.szy.douyou_gateway.config.util.JwtUtils;
import com.szy.douyou_gateway.dao.Users;
import com.szy.douyou_gateway.service.UsersService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author sunziyan
 * @date 2022/2/15
 */
@Component
public class AccountRealm extends AuthorizingRealm {

    @Resource
    JwtUtils jwtUtils;

    @Resource
    UsersService usersService;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("开始授权");
        return null;
    }

    /**
     * 获取token之后认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        JwtToken jwtToken = (JwtToken) authenticationToken;
        //从jwt中获取userId
        String userId = jwtUtils.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();

        Users user = usersService.getUserById(Long.valueOf(userId));

        if (user == null) {
            throw new UnknownAccountException("账号不存在");
        }


        //信息copy进VO
        AccountProfile profile = new AccountProfile();
        BeanUtil.copyProperties(user, profile);
        //将profile存进redis中
        return new SimpleAuthenticationInfo(profile, jwtToken.getCredentials(), getName());
    }
}
